package org.devops



//获取文件内容
def GetRepoFile(projectId, filePath, branchName) {
    // GET /projects/:id/repository/files/:file_path/raw
    def apiUrl = "/projects/${projectId}/repository/files/${filePath}/raw?ref=${branchName}"
    def response = HttpReq('GET', apiUrl)

    // 检查响应是否为空或不是字符串
    if (response == null || !(response instanceof String)) {
        throw new IllegalArgumentException("Failed to get valid file content from GitLab repository")
    }

    return response
}

//更新文件内容
def UpdateRepoFile(projectId,filePath,fileContent, branchName){
    apiUrl = "projects/${projectId}/repository/files/${filePath}"
    reqBody = """{"branch": "${branchName}","encoding":"base64", "content": "${fileContent}", "commit_message": "update a new file"}"""
    response = HttpReqByPlugin('PUT',apiUrl,reqBody)
    println(response)

}

//创建文件
def CreateRepoFile(projectId,filePath,fileContent, branchName){
    apiUrl = "projects/${projectId}/repository/files/${filePath}"
    reqBody = """{"branch": "${branchName}","encoding":"base64", "content": "${fileContent}", "commit_message": "update a new file"}"""
    response = HttpReqByPlugin('POST',apiUrl,reqBody)
    println(response)

}

// 封装HTTP
def HttpReqByPlugin(reqType, reqUrl,reqBody ){
    def gitServer = "http://gitlab.idevops.site/api/v4"
    withCredentials([string(credentialsId: '19379786-a088-4063-8cd6-5c39f22184dc', 
                            variable: 'GITLABTOKEN')]) {
        response = httpRequest acceptType: 'APPLICATION_JSON_UTF8', 
                    consoleLogResponseBody: true, 
                    contentType: 'APPLICATION_JSON_UTF8', 
                    customHeaders: [[maskValue: false, name: 'PRIVATE-TOKEN', value: "${GITLABTOKEN}"]], 
                    httpMode: "${reqType}", 
                    url: "${gitServer}/${reqUrl}", 
                    wrapAsMultipart: false,
                    requestBody: "${reqBody}"

    }
    return response
}


//发起HTTP请求
def HttpReq(method, apiUrl){
    withCredentials([string(credentialsId: '19379786-a088-4063-8cd6-5c39f22184dc', 
                            variable: 'gitlabtoken')]) {
        response = sh  returnStdout: true, 
        script: """ 
            curl --location --request ${method} \
            http://gitlab.idevops.site/api/v4/${apiUrl} \
            --header "PRIVATE-TOKEN: ${gitlabtoken}"
        """
    }
     try {
        response = readJSON text: response - "\n"
    } catch(e){
        println(e)
    }
    return response
}

//获取ProjectID
def GetProjectIDByName(projectName, groupName){
    apiUrl = "projects?search=${projectName}"
    response = HttpReq("GET", apiUrl)
    if (response != []){
        for (p in response) {
            if (p["namespace"]["name"] == groupName){
                return response[0]["id"]
            }
        }
    }
}

//获取分支CommitID
def GetBranchCommitID(projectID, branchName){
    apiUrl = "projects/${projectID}/repository/branches/${branchName}"
    response = HttpReq("GET", apiUrl)
    return response.commit.short_id
}






//更新deployment.yaml image

import org.apache.commons.codec.binary.Base64

// 统一的 HTTP 请求方法
def sendRequest(method, apiUrl, reqBody = null, gitlabTokenCredentialId) {
    def gitServer = "http://gitlab.idevops.site/api/v4"
    def response

    withCredentials([string(credentialsId: gitlabTokenCredentialId, variable: 'gitlabtoken')]) {
        response = httpRequest(
            acceptType: 'APPLICATION_JSON_UTF8',
            consoleLogResponseBody: true,
            contentType: 'APPLICATION_JSON_UTF8',
            customHeaders: [[name: 'PRIVATE-TOKEN', value: gitlabtoken]],
            httpMode: method,
            url: "${gitServer}/${apiUrl}",
            requestBody: reqBody
        )
    }

    println("HTTP ${method} Request to ${apiUrl}: ${response}")

    return response
}

// 从 GitLab 中获取文件内容
def getFileContentFromGitLab(projectId, deployFile, branchName, gitlabTokenCredentialId) {
    def encodedFilePath = URLEncoder.encode(deployFile, "UTF-8")
    def apiUrl = "/projects/${projectId}/repository/files/${encodedFilePath}/raw?ref=${branchName}"

    println("Getting file content from ${apiUrl}")

    try {
        def response = sendRequest('GET', apiUrl, null, gitlabTokenCredentialId)

        if (response.status != 200) {
            throw new IllegalArgumentException("Failed to get valid file content from GitLab repository. Response status: ${response.status}")
        }

        return response.content
    } catch (FileNotFoundException e) {
        println("File '${deployFile}' not found in GitLab repository.")
        throw e
    }
}

// 更新或创建 GitLab 中的文件
def updateOrCreateFileInGitLab(projectId, deployFile, fileContent, branchName, commitMessage, commitUsername, gitlabTokenCredentialId) {
    def encodedFilePath = URLEncoder.encode(deployFile, "UTF-8")
    def apiUrl = "/projects/${projectId}/repository/files/${encodedFilePath}"
    def encodedFileContent = Base64.encodeBase64String(fileContent.getBytes("UTF-8"))

    def reqBody = """{
        "branch": "${branchName}",
        "encoding": "base64",
        "content": "${encodedFileContent}",
        "commit_message": "${commitMessage}",
        "author_email": "${commitUsername}@jenkins.com",
        "author_name": "${commitUsername}"
    }"""

    println("Updating or creating file ${deployFile} in GitLab...")

    try {
        def response = sendRequest('PUT', apiUrl, reqBody, gitlabTokenCredentialId)
        if (response.status != 200) {
            // 如果文件不存在,则创建文件
            response = sendRequest('POST', apiUrl, reqBody, gitlabTokenCredentialId)
            if (response.status == 201) {
                println("File ${deployFile} created successfully.")
            } else {
                println("Failed to create file ${deployFile}: ${response.content}")
            }
        }
    } catch (IOException e) {
        println("Failed to update or create file ${deployFile}: ${e.message}")
        throw e
    }

    
}

// 更新部署文件
def updateDeploymentArgoCD(params) {
    def projectId = params.projectId
    def dockerImageName = params.dockerImageName
    def deployFile = params.deployFile
    def branchName = params.branchName
    def commitMessage = params.commitMessage
    def commitUsername = params.commitUsername
    def gitlabTokenCredentialId = params.gitlabTokenCredentialId

    println("Updating deployment for ${deployFile}...")

    // 验证文件路径和分支名称
    if (!deployFile || !branchName) {
        println("Invalid deployFile or branchName provided.")
        return
    }

    // 获取文件内容
    def fileContent
    try {
        fileContent = getFileContentFromGitLab(projectId, deployFile, branchName, gitlabTokenCredentialId)
    } catch (Exception e) {
        println("Failed to retrieve file ${deployFile}: ${e.message}")
        return // 结束更新流程,不再继续执行
    }

    if (fileContent == null || fileContent.isEmpty()) {
        println("File ${deployFile} does not exist in the remote repository.")
        return
    }

    // 更新镜像地址
    def updatedFileContent = fileContent.replaceAll(/image:\s*\S+/, "image: ${dockerImageName}")

    // 更新或创建文件
    updateOrCreateFileInGitLab(projectId, deployFile, updatedFileContent, branchName, commitMessage, commitUsername, gitlabTokenCredentialId)

    println("Updated file content:")
    println(updatedFileContent)

    return true
}